//
//  MXCreateBeltView.m
//  MXUserSys
//
//  Created by 王启颖 on 2018/10/12.
//  Copyright © 2018年 王启颖. All rights reserved.
//

#import "MXCreateBeltView.h"
#import "LZPickerView.h"
#import "ZLDefine.h"
#import <Photos/Photos.h>
#import "WLDecimalKeyboard.h"

#import <PPNetworkHelper.h>

@interface MXCreateBeltView ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *manufactorBtn;
@property (weak, nonatomic) IBOutlet UITextField *pirceNumTextField;
@property (nonatomic,strong) LZPickerView *lzPickerVIew;
@property (nonatomic,assign) NSNumber *manufactor_id;
@property (weak, nonatomic) IBOutlet UIImageView *beltImgV;
@property (weak, nonatomic) IBOutlet UIButton *createBtn;
@property (weak, nonatomic) IBOutlet UITextField *totalProductionTextField;
@property (weak, nonatomic) IBOutlet UITextField *styleTextField;
@property (nonatomic,assign) NSString *url;
@property (strong, nonatomic) NSString *assetsUrl_Str;
@property (nonatomic,assign) BOOL isUpdate;
@property (weak, nonatomic) IBOutlet UIButton *photoBtn;
@property (strong, nonatomic) NSArray *photoDataArray;
@end
@implementation MXCreateBeltView

- (void)awakeFromNib {
    [super awakeFromNib];
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"LZPickerView" owner:nil options:nil];
    self.lzPickerVIew  = views[0];
    
    [self initCustomerControls];
}

- (void)initCustomerControls {
    //创建键盘
    WLDecimalKeyboard *inputView = [[WLDecimalKeyboard alloc] init];
    self.pirceNumTextField.delegate = self;
    self.pirceNumTextField.backgroundColor = [UIColor whiteColor];
    self.pirceNumTextField.placeholder = @"请输入单价";
    self.pirceNumTextField.inputView = inputView;
    [self.pirceNumTextField reloadInputViews];
    
    self.totalProductionTextField.delegate = self;
    self.totalProductionTextField.backgroundColor = [UIColor whiteColor];
    self.totalProductionTextField.placeholder = @"请输入总数";
    self.totalProductionTextField.inputView = inputView;
    [self.totalProductionTextField reloadInputViews];
    
    self.styleTextField.placeholder = @"请输入款号";
    
    [self.createBtn changeCornerRadius:self.createBtn.height/2];
}

- (void)setModel:(MXHomePageModel *)model{
    _model = model;
    
    [self.createBtn setTitle:@"修改花带" forState:UIControlStateNormal];
    [self.photoBtn setTitle:@"这个不能改哦" forState:UIControlStateNormal];
    
    self.pirceNumTextField.text = model.price;
    self.totalProductionTextField.text = model.total_production;
    self.manufactor_id = @([model.manufactor_id integerValue]);
    
    [[MXAccount sharedMXAccount] LoadManufactorFromSandbox];
    NSArray *manufactorArr = [MXAccount sharedMXAccount].manufactorArr;

    for (int i = 0; i<manufactorArr.count; i++) {
        NSDictionary *dic = manufactorArr[i];
        NSNumber *id = dic[@"manufactor_id"];
        if ([id integerValue] == [model.manufactor_id integerValue]) {
            [self.manufactorBtn setTitle:dic[@"manufactor_name"] forState:UIControlStateNormal];
        }
    }
    
    self.styleTextField.text = model.style;
    self.isUpdate = YES;
    [self.photoBtn setUserInteractionEnabled:NO];
    
    [self.beltImgV sd_setImageWithURL:[NSURL URLWithString:model.belt_pic] placeholderImage:[UIImage imageNamed:@"photoAndVideoDefault"]];
}

#pragma mark - 点击事件 -
- (IBAction)manufactorBtnClick:(id)sender {
    [_pirceNumTextField resignFirstResponder];
    [_totalProductionTextField resignFirstResponder];
    
    UIButton *btn = (id)sender;
    [[MXAccount sharedMXAccount] LoadManufactorFromSandbox];
    NSArray *manufactorArr = [MXAccount sharedMXAccount].manufactorArr;
    NSMutableArray *factorNameArr = [[NSMutableArray alloc]init];
    NSMutableArray *factorIdArr = [[NSMutableArray alloc]init];
    for (int i = 0; i<manufactorArr.count; i++) {
        NSDictionary *dic = manufactorArr[i];
        NSString *name = dic[@"manufactor_name"];
        NSNumber *id = dic[@"manufactor_id"];
        [factorNameArr addObject:name];
        [factorIdArr addObject:id];
    }
    
    [self.lzPickerVIew lzPickerVIewType:LZPickerViewTypeSexAndHeight];
    self.lzPickerVIew.dataSource = factorNameArr;
    self.lzPickerVIew.titleText = @"厂家";
    __weak typeof(self) weakself = self;
    self.lzPickerVIew.selectValue = ^(NSString *value, NSInteger row) {
        [btn setTitle:value forState:UIControlStateNormal];
        NSNumber *id = factorIdArr[row];
        weakself.manufactor_id = id;
    };
    [self.lzPickerVIew show];
}

- (IBAction)photoBtnClick:(UIButton *)sender {
    [_pirceNumTextField resignFirstResponder];
    [_totalProductionTextField resignFirstResponder];
    [_styleTextField resignFirstResponder];
    
    ZLOnePhoto *one = [ZLOnePhoto shareInstance];
    
    
    
    
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [one presentPicker:PickerType_Camera photoCut:PhotoCutType_YES target:self.viewController callBackBlock:^(UIImage *image, BOOL isCancel) {
            self.beltImgV.image = image;
            [self saveImage:image];
        }];
    }]];
    
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [one presentPicker:PickerType_Photo photoCut:PhotoCutType_YES target:self.viewController callBackBlock:^(UIImage *image, BOOL isCancel) {
            self.beltImgV.image = image;
            [self saveImage:image];
        }];
        
    }]];
    
    [self.viewController presentViewController:alertController animated:YES completion:nil];
    
}

- (IBAction)createBeltClick:(id)sender {
    [_pirceNumTextField resignFirstResponder];
    [_totalProductionTextField resignFirstResponder];
    [_styleTextField resignFirstResponder];
    
    [self createOrUpdateBelt];
}



#pragma mark - UITextFieldDelegate -
/// 设置自定义键盘后，delegate 不会被调用？
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSLog(@"%@", [textField.text stringByReplacingCharactersInRange:range withString:string]);
    
    return YES;
}

#pragma mark - 懒加载 -
-(BOOL)isUpdate{
    if (!_isUpdate) {
        _isUpdate = NO;
    }
    return _isUpdate;
}

#pragma mark - 网络请求 -
-(void)createOrUpdateBelt{
    
    
    MXUserMessage *usermessage = [MXUserMessageTool message];
    MXHomePageModel *model = [[MXHomePageModel alloc]init];
    [model setPrice:_pirceNumTextField.text];
    [model setOperator_user:usermessage.nickname];
    [model setManufactor_id:[self.manufactor_id stringValue]];
    [model setTotal_production:self.totalProductionTextField.text];
    [model setStyle:self.styleTextField.text];
    
    
    if ([model.manufactor_id length] == 0){
        [SVProgressHUD showImage:NULL_IMAGE status:@"请选择厂家"];
        return;
    }else if ([model.needle_num length] > 8){
        [SVProgressHUD showImage:NULL_IMAGE status:@"针数过大"];
        return;
    }else if ([model.total_production length] > 8){
        [SVProgressHUD showImage:NULL_IMAGE status:@"总数过大"];
        return;
    }else if ([model.needle_num length] == 0){
        model.needle_num = @"0";
    }else if ([model.total_production length] == 0){
        model.total_production = @"0";
    }
    
    if (self.isUpdate) {
        [self updateBeltRequest:model];
    }else{
        [self createBeltRequest:model];
    }

}

-(void)updateBeltRequest:(MXHomePageModel *)model{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    params[@"operator_user"] = model.operator_user;
    params[@"price"] = model.price;
    params[@"manufactor_id"] = model.manufactor_id;
    params[@"total_production"] = model.total_production;
    params[@"style"] = model.style;
    params[@"id"] = self.model.id;
    
    [[MXHttpManagerClass HttpRequstManager] PostURL:updateBelt params:params isHearderparam:YES success:^(NSInteger code, id result) {
        
        if (code == 0) {
            NSLog(@"%@",result);
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [SVProgressHUD showImage:NULL_IMAGE status:@"参数错误"];
        }
        
    } fail:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
}


-(void)createBeltRequest:(MXHomePageModel *)model{
    if ([self.assetsUrl_Str length] == 0 ) {
        return;
    }
    
    [MXPublicRequstClass uploadImg:self.assetsUrl_Str success:^(id result) {
        [model setBelt_pic:[NSString stringWithFormat:@"%@%@",Img_URL,result[@"key"]]];
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        params[@"operator_user"] = model.operator_user;
        params[@"price"] = model.price;
        params[@"manufactor_id"] = model.manufactor_id;
        params[@"total_production"] = model.total_production;
        params[@"style"] = model.style;
        params[@"belt_pic"] = model.belt_pic;

        [[MXHttpManagerClass HttpRequstManager] PostURL:createBelt params:params isHearderparam:YES success:^(NSInteger code, id result) {
            
            if (code == 0) {
                NSLog(@"%@",result);
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [SVProgressHUD showImage:NULL_IMAGE status:@"参数错误"];
            }
            
        } fail:^(NSError *error) {
            
            NSLog(@"%@",error);
        }];
    }];
}



#pragma mark - 图片数组赋值 -
- (void)saveImage:(UIImage *)image {
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSData *data = [self resetSizeOfImageData:image maxSize:kScreenWidth];
    UIImage *resultImage = [UIImage imageWithData:data];
    
    NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:
                          [NSString stringWithFormat:@"demo.png"]];  // 保存文件的名称
    
    BOOL result =[UIImagePNGRepresentation(resultImage)writeToFile:filePath   atomically:YES]; // 保存成功会返回YES
    if (result == YES) {
        NSLog(@"保存成功");
        self.assetsUrl_Str = filePath;
    }
    
}

//压缩照片
- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize {
    //先判断当前质量是否满足要求，不满足再进行压缩
    __block NSData *finallImageData = UIImageJPEGRepresentation(source_image,1.0);
    
    NSLog(@"---------------不压缩：%li",finallImageData.length/1024);
    NSUInteger sizeOrigin   = finallImageData.length;
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    
    if (sizeOriginKB <= maxSize) {
        return finallImageData;
    }
    
    //先调整分辨率
    CGSize defaultSize = CGSizeMake(1024, 1024);
    UIImage *newImage = [self newSizeImage:defaultSize image:source_image];
    
    finallImageData = UIImageJPEGRepresentation(newImage,1.0);
    
    //保存压缩系数
    NSMutableArray *compressionQualityArr = [NSMutableArray array];
    CGFloat avg   = 1.0/250;
    CGFloat value = avg;
    for (int i = 250; i >= 1; i--) {
        value = i*avg;
        [compressionQualityArr addObject:@(value)];
    }
    /*
     调整大小
     说明：压缩系数数组compressionQualityArr是从大到小存储。
     */
    //思路：使用二分法搜索
    finallImageData = [self halfFuntion:compressionQualityArr image:newImage sourceData:finallImageData maxSize:maxSize];
    //如果还是未能压缩到指定大小，则进行降分辨率
    while (finallImageData.length == 0) {
        //每次降100分辨率
        if (defaultSize.width-100 <= 0 || defaultSize.height-100 <= 0) {
            break;
        }
        defaultSize = CGSizeMake(defaultSize.width-100, defaultSize.height-100);
        UIImage *image = [self newSizeImage:defaultSize
                                      image:[UIImage imageWithData:UIImageJPEGRepresentation(newImage,[[compressionQualityArr lastObject] floatValue])]];
        finallImageData = [self halfFuntion:compressionQualityArr image:image sourceData:UIImageJPEGRepresentation(image,1.0) maxSize:maxSize];
    }
    NSLog(@"---------------压缩后：%li",finallImageData.length/1024);
    return finallImageData;
}

//调整图片分辨率/尺寸（等比例缩放）
- (UIImage *)newSizeImage:(CGSize)size image:(UIImage *)source_image {
    CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);
    
    CGFloat tempHeight = newSize.height / size.height;
    CGFloat tempWidth = newSize.width / size.width;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
    }
    else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
    }
    
    UIGraphicsBeginImageContext(newSize);
    [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

//二分法
- (NSData *)halfFuntion:(NSArray *)arr image:(UIImage *)image sourceData:(NSData *)finallImageData maxSize:(NSInteger)maxSize {
    NSData *tempData = [NSData data];
    NSUInteger start = 0;
    NSUInteger end = arr.count - 1;
    NSUInteger index = 0;
    
    NSUInteger difference = NSIntegerMax;
    while(start <= end) {
        index = start + (end - start)/2;
        
        finallImageData = UIImageJPEGRepresentation(image,[arr[index] floatValue]);
        
        NSUInteger sizeOrigin = finallImageData.length;
        NSUInteger sizeOriginKB = sizeOrigin / 1024;
        //        NSLog(@"当前降到的质量：%ld", (unsigned long)sizeOriginKB);
        //        NSLog(@"\nstart：%zd\nend：%zd\nindex：%zd\n压缩系数：%lf", start, end, (unsigned long)index, [arr[index] floatValue]);
        
        if (sizeOriginKB > maxSize) {
            start = index + 1;
        } else if (sizeOriginKB < maxSize) {
            if (maxSize-sizeOriginKB < difference) {
                difference = maxSize-sizeOriginKB;
                tempData = finallImageData;
            }
            if (index<=0) {
                break;
            }
            end = index - 1;
        } else {
            break;
        }
    }
    return tempData;
}



+ (instancetype)initMXCreateBeltView {
    return NSbunleloadNibName(@"MXCreateBeltView");
}

@end
